package com.lxq.LeetCode.addTwoNumbers;

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}

class Solution {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3, null)));
        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4, null)));
        ListNode resNode = addTwoNumbers(l1, l2);
        System.out.println(resNode.toString());
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int temp = 0;
        ListNode resNode = new ListNode();
        ListNode p1, p2, pr;
        p1 = l1;
        p2 = l2;
        pr = resNode;
        while (p1 != null || p2 != null) {
            int sum = 0;
            if (p1 != null && p2 != null) {
                sum = p1.val + p2.val + temp;
            } else if (p1 == null) {
                sum = p2.val + temp;
            } else if (p2 == null) {
                sum = p1.val + temp;
            }

            if (sum < 10) {
                pr.val = sum;
                temp = 0;
            } else {
                pr.val = sum - 10;
                temp = 1;
            }

            if (p1 != null) {
                p1 = p1.next;
            }
            if (p2 != null) {
                p2 = p2.next;
            }
            if (p1 != null || p2 != null || temp != 0) {
                pr.next = new ListNode();
                pr = pr.next;
            }
            if (p1 == null && p2 == null && temp != 0) {
                pr.val = temp;
            }


        }
        return resNode;
    }
}